/*
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.firebase.ai.type

import kotlinx.serialization.Serializable

/**
 * A response from the model.
 *
 * @property candidates The list of [Candidate] responses generated by the model.
 * @property promptFeedback Feedback about the prompt send to the model to generate this response.
 * When streaming, it's only populated in the first response.
 * @property usageMetadata Information about the number of tokens in the prompt and in the response.
 */
public class GenerateContentResponse(
  public val candidates: List<Candidate>,
  public val promptFeedback: PromptFeedback?,
  public val usageMetadata: UsageMetadata?,
) {
  /**
   * Convenience field representing all the text parts in the response as a single string.
   *
   * The value is null if the response contains no valid text [candidates].
   *
   * Any part that's marked as a thought will be ignored. Learn more about
   * [thinking](https://firebase.google.com/docs/ai-logic/thinking?api=dev).
   */
  public val text: String? by lazy {
    val parts = candidates.firstOrNull()?.nonThoughtParts()?.filterIsInstance<TextPart>()
    if (parts.isNullOrEmpty()) return@lazy null
    parts.joinToString(" ") { it.text }
  }

  /**
   * Convenience field to list all the [FunctionCallPart]s in the response.
   *
   * The value is an empty list if the response contains no [candidates].
   *
   * Any part that's marked as a thought will be ignored. Learn more about
   * [thinking](https://firebase.google.com/docs/ai-logic/thinking?api=dev).
   */
  public val functionCalls: List<FunctionCallPart> by lazy {
    candidates.firstOrNull()?.nonThoughtParts()?.filterIsInstance<FunctionCallPart>().orEmpty()
  }

  /**
   * Convenience field representing all the text parts in the response that are marked as thoughts
   * as a single string, if they exist.
   *
   * Learn more about [thinking](https://firebase.google.com/docs/ai-logic/thinking?api=dev).
   */
  public val thoughtSummary: String? by lazy {
    candidates.firstOrNull()?.thoughtParts()?.filterIsInstance<TextPart>()?.joinToString(" ") {
      it.text
    }
  }

  /**
   * Convenience field representing all the [InlineDataPart]s in the first candidate.
   *
   * This also includes any [ImagePart], but they will be represented as [InlineDataPart] instead.
   *
   * The value is an empty list if the response contains no [candidates].
   *
   * Any part that's marked as a thought will be ignored. Learn more about
   * [thinking](https://firebase.google.com/docs/ai-logic/thinking?api=dev).
   */
  public val inlineDataParts: List<InlineDataPart> by lazy {
    candidates
      .firstOrNull()
      ?.nonThoughtParts()
      ?.let { parts ->
        parts.filterIsInstance<ImagePart>().map { it.toInlineDataPart() } +
          parts.filterIsInstance<InlineDataPart>()
      }
      .orEmpty()
  }

  private fun Candidate.thoughtParts(): List<Part> = content.parts.filter { it.isThought }

  private fun Candidate.nonThoughtParts(): List<Part> = content.parts.filter { !it.isThought }

  @Serializable
  internal data class Internal(
    val candidates: List<Candidate.Internal>? = null,
    val promptFeedback: PromptFeedback.Internal? = null,
    val usageMetadata: UsageMetadata.Internal? = null,
  ) : Response {
    internal fun toPublic(): GenerateContentResponse {
      return GenerateContentResponse(
        candidates?.map { it.toPublic() }.orEmpty(),
        promptFeedback?.toPublic(),
        usageMetadata?.toPublic()
      )
    }
  }
}
